﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Text;
using System.Configuration;
using System.IO;
using System.Xml;

using ECCIT;
using OgilvyOne.Ext.Weibo.Common;
using OgilvyOne.Ext.Weibo.Configuration;
using OgilvyOne.Ext.Weibo.Lib;
using OgilvyOne.Sharan.Model;
using OgilvyOne.Sharan.BLL;
using OgilvyOne.Sharan.ProcessFlow;

namespace OgilvyOne.Sharan.Web.Weibo
{
    using Environment_v2 = OgilvyOne.Ext.Weibo.Configuration.Environment;
    using OAuthAccessToken_v2 = OgilvyOne.Ext.Weibo.Common.OAuthAccessToken;
    using Microblog_v2 = OgilvyOne.Ext.Weibo.Lib.Microblog;
    using UserInfo_v2 = OgilvyOne.Ext.Weibo.Model.UserInfo;
    using Users_v2 = OgilvyOne.Ext.Weibo.Model.Users;
    using MicroblogException_v2 = OgilvyOne.Ext.Weibo.Common.MicroblogException;
    using Source_v2 = OgilvyOne.Ext.Weibo.Model.Source;

    public class SessionNullException : Exception
    {
        
    }

    public partial class XmlHttpGate : System.Web.UI.Page
    {
        private const string SUCCESS = "<result>1</result>";
        private const string FAILURE = "<result>0</result>";
        private const string RESULT = "<result>{0}</result>";
        private const string RESULT_MESSAGE = "<result message=\"{0}\">{1}</result>";
        private const string HEADER = "<?xml version=\"1.0\" encoding=\"utf-8\" ?>";

        protected void Page_Load(object sender, EventArgs e)
        {
            Response.ContentType = "text/xml";
            Response.ContentEncoding = Encoding.UTF8;

            try
            {
                string operation = Request.Params["op"];
                string output = null;
                WeiboUserBLL bll = new WeiboUserBLL();
                LikeCountBLL likeBll = new LikeCountBLL();
                AccountController controller = new AccountController();

                if (operation == null)          // 获取7个KOL每人最新的7条微博数据接口
                {
                    //try
                    //{
                    //    string statusTag = ConfigCacheManager.StatusTag;
                    //    output = bll.GetUserLatestStatusAboutSharan(statusTag);
                    //}
                    //catch (Exception e1)
                    //{
                    //    throw new Exception("Error occurred in GetUserLatestStatusAboutSharan. Message: " + e1.Message);
                    //}
                }
                else if (operation == "1")      // 判断是否使用新浪微博账号登录
                {
                    if (controller.WeiboUserID == null) throw new SessionNullException();
                    output = string.Format(RESULT, controller.WeiboUserID.Value);

                    //DateTime? dt = (DateTime?)Application["ExpireTime"];
                    //if (dt.HasValue)
                    //{
                    //    if (dt.Value.Subtract(DateTime.Now).TotalSeconds < 86000)
                    //        output = string.Format(RESULT, controller.WeiboUserID.Value);
                    //    else
                    //        output = FAILURE;
                    //}
                    //else
                    //{
                    //    output = FAILURE;
                    //}
                }
                else if (operation == "2")      // 使用新浪微博账号登录后新浪回调接口,用于保存access_token和写用户session
                {
                    // 新浪登录页面回调接口，用来写session和写access_token
                    object o = Request.QueryString["access_token"];
                    if (o == null) throw new ArgumentNullException("access_token");

                    string accessToken = (string)o;
                    OAuthAccessToken_v2 token = new OAuthAccessToken_v2();
                    token.Token = accessToken;
                    controller.AccessToken = token;

                    // 写session
                    string sUserID = Request.Params["uid"];
                    controller.WeiboUserID = long.Parse(sUserID);

                    // 写Environment
                    //OAuthAccessToken_v2 token = new OAuthAccessToken_v2();
                    //token.Token = accessToken;
                    Environment_v2.AccessToken = token;
                    //Environment_v2.AccessToken.UserID = sUserID;

                    output = SUCCESS;
                }
                else if (operation == "3")      // 用于获取用户好友每人最新一条微博数据
                {
                    if (controller.WeiboUserID == null) throw new SessionNullException();

                    //Environment_v2.AccessToken.UserID = controller.WeiboUserID.ToString();
                    string uri = "";
                    try
                    {
                        //output = bll.GetActiveFollowerStatuses(userID);
                        // 从数据表中取出用户设置的好友，获取微博数据
                        output = bll.GetFriendStatuses(controller.WeiboUserID.Value, out uri);
                    }
                    catch (Exception exg)
                    {
                        throw new Exception("Error occurred in XmlHttpGate. uri:" + uri);
                    }
                }
                else if (operation == "4")      // 用于接收二进制流,并保存成图片,然后返回图片链接给Flash
                {
                    Stream stream = Request.InputStream;
                    long length = stream.Length;
                    byte[] buffer = new byte[length];
                    int readCount = stream.Read(buffer, 0, Convert.ToInt32(length));

                    string imageName = "/uploadfiles/" + Guid.NewGuid().ToString() + ".jpg";
                    string fileName = Server.MapPath(imageName);
                    FileStream pFileStream = null;
                    try
                    {
                        pFileStream = new FileStream(fileName, FileMode.OpenOrCreate);
                        pFileStream.Write(buffer, 0, readCount);
                        output = string.Format("<result value=\"1\">{0}</result>", ".." + imageName);
                    }
                    catch (Exception ex)
                    {
                        output = string.Format("<result value=\"0\">{0}</result>", ex.Message);
                    }
                    finally
                    {
                        if (pFileStream != null)
                            pFileStream.Close();
                    }
                }
                else if (operation == "6")      // 判断当前登录用户是否在我们的系统设置过自己的好友
                {
                    // 判断用户是否曾经创建过我的周刊
                    if (controller.WeiboUserID == null) throw new SessionNullException();

                    //string sUid = Request.Params["uid"];
                    //if (string.IsNullOrEmpty(sUid)) throw new ArgumentNullException("uid");

                    long? uid = controller.WeiboUserID;
                    WeiboRelationBLL relationBll = new WeiboRelationBLL();
                    List<long?> friends = relationBll.GetFriendWeiboUserIDs(uid);

                    if (friends == null)
                        output = FAILURE;
                    else if (friends.Count == 0)
                        output = FAILURE;
                    else
                        output = SUCCESS;
                }
                else if (operation == "7")      // 获取当前新浪微博登录用户的互粉好友数据
                {
                    if (controller.WeiboUserID == null) throw new SessionNullException();

                    string sPageIndex = Request.Params["pageIndex"];    // 从参数中接收页码
                    if (string.IsNullOrEmpty(sPageIndex)) throw new ArgumentNullException("pageIndex");

                    string search = Request.Params["search"];           // 从参数中接收查询条件
                    string sPageSize = Request.Params["pageSize"];      // 从参数中接收每页显示记录数

                    int currentPageIndex = int.Parse(sPageIndex);
                    int pageSize = string.IsNullOrEmpty(sPageSize) ? 10 : int.Parse(sPageSize);     // 默认每页显示10条数据

                    Users_v2 users = bll.GetFriends(controller.WeiboUserID.Value, pageSize, currentPageIndex, search);  // 获取分页数据

                    int totalNumber = users.TotalNumber;
                    int pageCount = (totalNumber % pageSize == 0) ? totalNumber / pageSize : (totalNumber / pageSize) + 1;    // 计算页数

                    StringBuilder builder = new StringBuilder("<users total_count=\"" + totalNumber + "\" page_count=\"" + pageCount + "\" curr_page_index=\"" + currentPageIndex + "\">");
                    int selected = 0;
                    int i = 0;
                    foreach (UserInfo_v2 user in users.Items)
                    {
                        if (currentPageIndex == 0 && i < 7)
                            selected = 1;
                        else
                            selected = 0;

                        builder.AppendFormat("<user id=\"{0}\" screen_name=\"{1}\" name=\"{2}\" profile_image_url=\"{3}\" avatar_large=\"{4}\" selected=\"{5}\"/>",
                            user.ID, user.ScreenName, user.Name, user.ProfileImageUrl, user.AvatarLarge, selected);
                        i++;
                    }
                    builder.Append("</users>");
                    output = builder.ToString();
                }
                else if (operation == "8")      // 提交用户选择的出现在我的周刊中的微博好友的数据
                {
                    if (controller.WeiboUserID == null) throw new SessionNullException();

                    string uids = Request.Params["uids"];
                    if (string.IsNullOrEmpty(uids)) throw new ArgumentNullException("uids");

                    ResultInfo result = new ResultInfo(false);
                    try
                    {
                        long? uid = controller.WeiboUserID;
                        JoinedString uidStr = new JoinedString(uids, ",");
                        Session["uids"] = uids;

                        List<long?> uidList = new List<long?>();
                        foreach (string u in uidStr)
                        {
                            if (long.Parse(u) > 0)
                                uidList.Add(long.Parse(u));
                        }

                        WeiboRelationBLL relationBll = new WeiboRelationBLL();
                        result = relationBll.Save(uid, uidList);
                    }
                    catch (Exception ex)
                    {
                        result.Message = "Error occurred in operation 8. Message:" + ex.Message;
                    }
                    output = (result.Result) ? SUCCESS : string.Format(RESULT_MESSAGE, result.Message);
                }
                else if (operation == "10")
                {
                    output = string.Format(RESULT, controller.Random);
                }
                else if (operation == "5")      // 获取7个KOL每人最新的7条微博数据接口
                {
                    try
                    {
                        //object objTime = Application["LastCallTime"];
                        //if (objTime != null)
                        //{
                        //    DateTime dt = (DateTime)objTime;
                        //    if (DateTime.Now.Subtract(dt).TotalSeconds > 3600)
                        //    {
                        //        output = bll.GetUserLatestStatusAboutSharan_v2(controller.AccessToken, ConfigCacheManager.StatusTag);
                        //        Application["LastCallTime"] = DateTime.Now;
                        //        Cache["CACHE_KEY_KOL"] = output;
                        //    }
                        //    else
                        //    {
                        //        output = (string)Cache["CACHE_KEY_KOL"];
                        //        if (output == "<users></users>")
                        //        {
                        //            output = bll.GetUserLatestStatusAboutSharan_v2(controller.AccessToken, ConfigCacheManager.StatusTag);
                        //            Application["LastCallTime"] = DateTime.Now;
                        //            Cache["CACHE_KEY_KOL"] = output;
                        //        }
                        //    }
                        //}
                        //else
                        //{
                        //    output = bll.GetUserLatestStatusAboutSharan_v2(controller.AccessToken, ConfigCacheManager.StatusTag);
                        //    Application["LastCallTime"] = DateTime.Now;
                        //    Cache["CACHE_KEY_KOL"] = output;
                        //}

                        if (Cache["CACHE_KEY_KOL"] == null)
                        {
                            // 比较取回的数据和文件中数据谁更全面，将更全面的存入缓存并返回
                            string filePath = Server.MapPath("CacheData/PersonateKOLStatuses.xml");
                            string cacheData = File.ReadAllText(filePath, Encoding.UTF8);

                            output = cacheData.Replace("<users>", "<users source=\"file\">");
                            Cache["CACHE_KEY_KOL"] = output;
                        }
                        else
                        {
                            output = Cache["CACHE_KEY_KOL"].ToString();
                        }
                    }
                    catch (Exception exg)
                    {
                        throw new Exception("Error occurred in get_kol. Message:" + exg.Message);
                    }
                }
                else if (operation == "11")
                {
                    try
                    {
                        long userID = long.Parse(Request.Params["uid"]);
                        UserInfo_v2 userInfo = Microblog_v2.GetUserInfoByAppkey(userID);
                        output = string.Format(RESULT, userInfo.LatestStatus.Text);
                    }
                    catch (Exception exg)
                    {
                        throw new Exception("Error occurred in 11. Message:" + exg.Message);
                    }
                }
                else if (operation == "get_application")
                {
                    string key = Request.Params["key"];
                    output = "<result>" + Application[key] + "</result>";
                }
                else if (operation == "get_token")
                {
                    string token = (controller.AccessToken == null) ? "NULL" : controller.AccessToken.Token;
                    output = "<result>" + token + "</result>";
                }
                else if (operation == "reset_app")
                {
                    Application["LastCallTime"] = null;
                }
                else if (operation == "reset_cache")
                {
                    Cache["CACHE_KEY_KOL"] = null;
                    output = "<result>" + Cache["CACHE_KEY_KOL"] + "</result>";
                }
                else if (operation == "get_session")
                {
                    string key = Request.Params["key"];
                    output = "<result>" + Session[key] + "</result>";
                }
                else if (operation == "get_status")
                {
                    output = bll.GetUserLatestStatusAboutSharan_v2(controller.AccessToken, ConfigCacheManager.StatusTag);
                }
                else if (operation == "get_user")
                {
                    long uid = long.Parse(Request.Params["uid"]);
                    UserInfo_v2 userInfo = Microblog_v2.GetUserInfo(controller.AccessToken, uid);
                    output = JsonSerializationHelper.ObjectToJson(userInfo);
                }
                else if (operation == "logout")
                {
                    Microblog_v2.Logout();
                    output = "<result>1</result>";
                }
                else if (operation == "getrepost")
                {
                    //Microblog_v2.rep
                }
                else if (operation == "get_rate")
                {
                    OgilvyOne.Ext.Weibo.Model.RateLimitStatus rs = Microblog_v2.GetRateLimitStatus();
                    if (rs != null)
                    {
                        output = "<result>1</result>";
                        output = "<result>" +
                            "<IPLimit>" + rs.IPLimit + "</IPLimit>";
                        output += "<RemainingIPHits>" + rs.RemainingIPHits + "</RemainingIPHits>";

                        if (rs.APIRateLimits != null && rs.APIRateLimits.Count > 0)
                        {
                            output += "<APIRateLimits count=\"" + rs.APIRateLimits.Count + "\">";

                            foreach (OgilvyOne.Ext.Weibo.Model.APIRateLimit rl in rs.APIRateLimits)
                            {
                                output += "<APIRateLimit>";
                                output += "<API>" + rl.API + "</API>";
                                output += "<Limit>" + rl.Limit + "</Limit>";
                                output += "<LimitTimeUnit>" + rl.LimitTimeUnit + "</LimitTimeUnit>";
                                output += "<RemainingHits>" + rl.RemainingHits + "</RemainingHits>";
                                output += "</APIRateLimit>";
                            }

                            output += "</APIRateLimits>";
                        }

                        output += "<LimitTimeUnit>" + rs.LimitTimeUnit + "</LimitTimeUnit>" +
                            "<RemainingUserHits>" + rs.RemainingUserHits + "</RemainingUserHits>" +
                            "<ResetTime>" + rs.ResetTime + "</ResetTime>" +
                            "<ResetTimeInSeconds>" + rs.ResetTimeInSeconds + "</ResetTimeInSeconds>" +
                            "<UserLimit>" + rs.UserLimit + "</UserLimit>" +
                            "</result>";
                    }
                    else
                    {
                        output = "<result>null</result>";
                    }
                }
                else if (operation == "get_like")
                {
                    string langID = Request.Params["lang"];
                    string sID = Request.Params["id"];
                    if (!string.IsNullOrEmpty(langID) && !string.IsNullOrEmpty(sID))
                    {
                        ResultInfo res = null;
                        int id = int.Parse(sID);
                        if (id > 0)
                        {
                            // 获取单个年代的计数
                            res = likeBll.GetMaxCount(int.Parse(langID), id);
                            if (res.Result)
                                output = HEADER + string.Format(RESULT, (long)res.ReturnObject);
                            else
                                output = HEADER + string.Format(RESULT, -1);
                        }
                        else
                        {
                            // 获取全部年代的计数
                            res = likeBll.GetModels(int.Parse(langID));
                            if (!res.Result)
                            {
                                output = HEADER + string.Format(RESULT_MESSAGE, res.Message, 0);
                            }
                            else
                            {
                                List<LikeCountModel> models = (List<LikeCountModel>)res.ReturnObject;
                                output = "<result>";
                                models.ForEach(delegate(LikeCountModel model)
                                {
                                    output += string.Format("<list years=\"{0}\" lan=\"{1}\">{2}</list>", model.ID, (model.LanguageID == 1033 ? "en" : "cn"), model.Count);
                                });
                                output += "</result>";
                                output = HEADER + output;
                            }
                        }
                    }
                }
                else if (operation == "inc_like")
                {
                    string langID = Request.Params["lang"];
                    string id = Request.Params["id"];
                    if (!string.IsNullOrEmpty(langID) && !string.IsNullOrEmpty(id))
                    {
                        ResultInfo res = likeBll.Increment(int.Parse(langID), int.Parse(id));
                        if (res.Result)
                        {
                            // 获取全部年代的计数
                            res = likeBll.GetModels(int.Parse(langID));
                            if (!res.Result)
                            {
                                output = HEADER + string.Format(RESULT_MESSAGE, res.Message, 0);
                            }
                            else
                            {
                                List<LikeCountModel> models = (List<LikeCountModel>)res.ReturnObject;
                                output = "<result>";
                                models.ForEach(delegate(LikeCountModel model)
                                {
                                    output += string.Format("<list years=\"{0}\" lan=\"{1}\">{2}</list>", model.ID, (model.LanguageID == 1033 ? "en" : "cn"), model.Count);
                                });
                                output += "</result>";
                                output = HEADER + output;
                            }
                        }
                        else
                            output = HEADER + string.Format(RESULT, -1);
                    }
                }

                Response.Write(output);
            }
            catch (SessionNullException sne)
            {
                Response.Write("<result error=\"session is null\">0</result>");
            }
            catch (ArgumentNullException ane)
            {
                Response.Write("<result error=\"argument is null\">0</result>");
            }
            catch (MicroblogException_v2 aex)
            {
                Response.Write(string.Format("<result errorCode=\"{0}\" errorMessage=\"{1}\">0</result>", aex.ErrorCode, aex.Message));
            }
            catch (Exception ex)
            {
                Response.Write("<Error><![CDATA[Error occurred in XmlHttpGate. Phase: 1. Message: " + ex.Message + "]]></Error>");
            }
        }
    }
}